<template>
  <div class="counselor-library">
    <!-- 标题与状态筛选 -->
    <div class="header">
      <div class="title">咨询师库</div>
      <div class="status-filter">
        <span
          :class="{ active: currentStatus === 'working' }"
          @click="currentStatus = 'working'"
        >
          工作中 ({{ workingCount }})
        </span>
        <span
          :class="{ active: currentStatus === 'leave' }"
          @click="currentStatus = 'leave'"
        >
          请假中 ({{ leaveCount }})
        </span>
      </div>
    </div>

    <!-- 查询区域 -->
    <div class="search-area">
      <el-input
        v-model="searchName"
        placeholder="请输入咨询师姓名查询"
        clearable
        style="width: 200px; margin-right: 10px"
      />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
      <!-- 操作按钮 -->
      <div class="operation-btns">
        <el-button type="primary" @click="showAddDialog('设置休息日')">休息日</el-button>
        <el-button type="primary" @click="showAddDialog('添加咨询师')">添加咨询师</el-button>
        <el-button type="primary" @click="handleExport">数据导出</el-button>
      </div>
    </div>

    <!-- 咨询师列表表格 -->
    <el-table :data="filteredCounselors" border style="width: 100%" class="main-table">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column prop="name" label="咨询师姓名" align="center" />
      <el-table-column prop="gender" label="咨询师性别" align="center" />
      <el-table-column prop="phone" label="联系电话" align="center" />
      <el-table-column label="咨询次数" align="center">
        <template #default="scope">
          {{ scope.row.consultCount }}次
          <span class="toggle-btn" @click="toggleConsultDetail(scope.row)">
            {{ isExpanded(scope.row) ? '收起' : '展开' }}
          </span>
        </template>
      </el-table-column>
      <!-- 变更工作状态列 -->
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <span
            @click="handleChangeStatus(scope.row)"
            style="cursor: pointer; color: #409eff"
          >
            {{ scope.row.status === 'working' ? '设置为休息' : '设置为工作' }}
          </span>
        </template>
      </el-table-column>
      <!-- 查看详情列 -->
      <el-table-column label="查看" align="center" width="100">
        <template #default="scope">
          <span
            @click="goToCounselorDetail(scope.row.id)"
            style="cursor: pointer; color: #409eff"
          >
            查看详情
          </span>
        </template>
      </el-table-column>
      <!-- 移除咨询师列 -->
      <el-table-column label="移除" align="center" width="100">
        <template #default="scope">
          <span
            @click="removeCounselor(scope.row.id)"
            style="cursor: pointer; color: #f56c6c"
          >
            移除咨询师
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 展开的咨询详情子表格（可根据实际需求调整数据渲染） -->
    <el-table
      v-for="(item, index) in expandedRows"
      :key="index"
      :data="item.studentList"
      border
      style="width: 100%; margin-top: 10px"
      class="sub-table"
    >
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column prop="studentName" label="学生姓名" align="center" />
      <el-table-column prop="gender" label="性别" align="center" />
      <el-table-column prop="studentId" label="学号" align="center" />
      <el-table-column prop="phone" label="联系电话" align="center" />
      <el-table-column prop="counselor" label="责任辅导员" align="center" />
      <el-table-column label="咨询优先级" align="center">
        <template #default="scope">
          <span :style="{ color: getPriorityColor(scope.row.priority) }">
            {{ getPriorityLabel(scope.row.priority) }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加咨询师和设置休息日抽屉 -->
    <el-drawer v-model="dialogFormVisible" direction="rtl">
      <template #header>
        <h4>{{titleName}}</h4>
      </template>
      <template #default>
        <el-form ref="form" :model="formData"  label-position="top" :rules="rules">
          <template v-if="titleName === '添加咨询师'">
            <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
              <el-input v-model="formData.name" autocomplete="off" placeholder="请输入咨询师姓名" />
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
              <el-radio-group v-model="formData.gender">
                <el-radio label="男性">男性</el-radio>
                <el-radio label="女性">女性</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
              <el-input v-model="formData.phone" autocomplete="off" placeholder="请输入联系电话" />
            </el-form-item>
          </template>
          <template v-if="titleName === '设置休息日'">
            <el-form-item label="休息日" :label-width="formLabelWidth" prop="holiday">
              <el-date-picker
                v-model="formData.holiday"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </template>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="titleName === '添加咨询师' ? addCounselor() : setHoliday()">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 咨询优先级配置
const priorityOptions = [
  { label: '即可评估', value: 'immediate', color: '#f56c6c' }, // 红色
  { label: '尽快评估', value: 'asap', color: '#e6a23c' },      // 黄色
  { label: '优先安排', value: 'prior', color: '#409eff' },      // 蓝色
  { label: '正常排队', value: 'normal', color: '#67c23a' },     // 绿色
];

// 获取优先级标签
const getPriorityLabel = (value: string) => {
  const option = priorityOptions.find(item => item.value === value);
  return option?.label || value;
};

// 获取优先级颜色
const getPriorityColor = (value: string) => {
  const option = priorityOptions.find(item => item.value === value);
  return option?.color || '#333';
};

// 随机生成姓名
const randomName = () => {
  const firstNames = ['张', '王', '李', '赵', '陈', '杨', '吴', '刘', '黄', '周'];
  const lastNames = ['伟', '芳', '娜', '敏', '静', '强', '磊', '军', '洋', '勇'];
  return firstNames[Math.floor(Math.random() * firstNames.length)] + lastNames[Math.floor(Math.random() * lastNames.length)];
};

// 随机生成电话号码
const randomPhone = () => {
  return '13' + Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
};

// 随机生成咨询详情子数据
const randomStudentList = () => {
  const count = Math.floor(Math.random() * 5); // 0 - 4 个学生
  const list = [];
  for (let i = 0; i < count; i++) {
    list.push({
      studentName: randomName(),
      gender: Math.random() > 0.5 ? '男性' : '女性',
      studentId: Math.floor(Math.random() * 10000).toString().padStart(5, '0'),
      phone: randomPhone(),
      counselor: randomName(),
      priority: priorityOptions[Math.floor(Math.random() * priorityOptions.length)].value,
    });
  }
  return list;
};

// 随机生成咨询师数据
const generateRandomCounselors = () => {
  const count = Math.floor(Math.random() * 5) + 3; // 3 - 7 个咨询师
  const counselors = [];
  for (let i = 0; i < count; i++) {
    const studentList = randomStudentList();
    counselors.push({
      id: i + 1,
      name: randomName(),
      gender: Math.random() > 0.5 ? '男性' : '女性',
      phone: randomPhone(),
      consultCount: studentList.length,
      status: Math.random() > 0.5 ? 'working' : 'leave',
      studentList,
    });
  }
  return counselors;
};

// 模拟原始咨询师数据（包含咨询详情子数据）
const counselors = ref(generateRandomCounselors());

// 状态筛选
const currentStatus = ref('working'); // 默认显示“工作中”
const workingCount = computed(() =>
  counselors.value.filter((item) => item.status === 'working').length
);
const leaveCount = computed(() =>
  counselors.value.filter((item) => item.status === 'leave').length
);

// 查询相关
const searchName = ref('');
const handleSearch = () => {
  // 简单实现：根据姓名模糊匹配，实际可结合接口
  filteredCounselors.value = counselors.value.filter((item) =>
    item.name.includes(searchName.value)
  );
};
const handleReset = () => {
  searchName.value = '';
  filteredCounselors.value = [...counselors.value];
};

// 筛选后的数据
const filteredCounselors = ref([...counselors.value]);

// 展开的咨询详情行（控制子表格显示）
const expandedRows = ref<any[]>([]);
const toggleConsultDetail = (row: any) => {
  const index = expandedRows.value.findIndex((item) => item.id === row.id);
  if (index > -1) {
    expandedRows.value.splice(index, 1);
  } else {
    expandedRows.value.push(row);
  }
};

// 判断当前行是否展开
const isExpanded = (row: any) => {
  return expandedRows.value.some((item) => item.id === row.id);
};

// 跳转详情逻辑
const goToCounselorDetail = (id: number) => {
  router.push({
    name: 'CounselorDetail',
    params: { counselorId: id },
  });
};

// 变更工作状态
const handleChangeStatus = (row: any) => {
  row.status = row.status === 'working' ? 'leave' : 'working';
  ElMessage.success(`已${row.status === 'working' ? '设置为工作' : '设置为休息'}`);
  handleReset();
};

// 移除咨询师
const removeCounselor = (id: number) => {
  counselors.value = counselors.value.filter((item) => item.id !== id);
  handleReset();
  ElMessage.success('移除咨询师成功');
};

// 抽屉相关
const dialogFormVisible = ref(false);
const titleName = ref('');
const form = ref(null);
const formLabelWidth = '140px';
const formData = ref({
  name: '',
  gender: '男性',
  phone: '',
  holiday: null,
});

const rules = {
  name: [
    { required: true, message: '请输入咨询师姓名', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
  ],
  holiday: [
    { required: true, message: '请选择休息日', trigger: 'change' },
  ],
};

const showAddDialog = (title: string) => {
  titleName.value = title;
  resetFormData();
  dialogFormVisible.value = true;
};

const resetFormData = () => {
  formData.value = {
    name: '',
    gender: '男性',
    phone: '',
    holiday: null,
  };
};

const addCounselor = () => {
  form.value.validate((valid: boolean) => {
    if (valid) {
      const newId = counselors.value.length + 1;
      const studentList = randomStudentList();
      counselors.value.push({
        id: newId,
        ...formData.value,
        consultCount: studentList.length,
        status: 'working',
        studentList,
      });
      handleReset();
      dialogFormVisible.value = false;
      ElMessage.success('添加咨询师成功');
    }
  });
};

const setHoliday = () => {
  form.value.validate((valid: boolean) => {
    if (valid) {
      console.log('设置休息日成功', formData.value.holiday);
      dialogFormVisible.value = false;
      ElMessage.success('设置休息日成功');
    } else {
      console.log('请完成表单填写');
    }
  });
};

// 数据导出
const handleExport = () => {
  const csvData = [
    ['咨询师姓名', '咨询师性别', '联系电话', '咨询次数', '工作状态'],
    ...counselors.value.map((item) => [
      item.name,
      item.gender,
      item.phone,
      item.consultCount,
      item.status === 'working' ? '工作中' : '请假中',
    ]),
  ];
  const csvContent = csvData.map((row) => row.join(',')).join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', 'counselors.csv');
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped lang="scss">
.counselor-library {
  padding: 20px;
  background-color: #fff;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .status-filter {
      span {
        margin-left: 20px;
        cursor: pointer;
        color: #666;
        &.active {
          color: #409eff;
          font-weight: bold;
        }
      }
    }
  }

  .search-area {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .operation-btns {
      margin-left: auto;
      button {
        margin-left: 10px;
      }
    }
  }

  .main-table {
    --el-table-header-text-color: #333;
    --el-table-row-hover-bg-color: #fafafa;

    .toggle-btn {
      color: #409eff;
      cursor: pointer;
      margin-left: 5px;
      font-size: 12px;
    }
  }

  .sub-table {
    --el-table-header-text-color: #666;
    --el-table-row-hover-bg-color: #f5f7fa;
    margin-top: 10px;
  }
}
</style>